<template>
  <div class="report">
    <div class="filter clearfix">
      <div class="left">
        <el-date-picker
          class="date-picker mgr10"
          v-model="dateRanges"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :unlink-panels="true"
          :default-time="['00:00:00', '23:59:59']"
          @change="dateChange">
        </el-date-picker>
        <el-select class="mgr10" v-model="departmentId" placeholder="请选择分公司">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in departmentList"
            :key="item.departmentId"
            :label="item.departmentName"
            :value="item.departmentId">
          </el-option>
        </el-select>
        <el-input class="searchbox mgr10" placeholder="请输入关键词" v-model="filterKeyword" clearable
                  @keyup.enter.native="handleSearch"></el-input>
        <el-button type="primary" :disabled="searchBtnLoading" :loading="searchBtnLoading" @click="handleSearch">搜索</el-button>
      </div>
    </div>
    <div class="btns clearfix">
      <div class="right">
        <a :href="exportUrl" download>
          <el-button>导出报表</el-button>
        </a>
      </div>
    </div>
    <div class="activity">
      <div class="title">
        <h3>活动数据</h3>
      </div>
      <div class="list activity-list">
        <el-table
          stripe
          v-loading="loading1"
          element-loading-text="拼命加载中"
          :data="activityTbData.list">
          <el-table-column label="活动标题" prop="name" min-width="120" fixed></el-table-column>
          <el-table-column label="活动时间" prop="activityDate" :formatter="getActivityDate" width="210"></el-table-column>
          <el-table-column label="分公司" prop="departmentName" min-width="120"></el-table-column>
          <el-table-column label="主体数量 (可分发人数量)" prop="mainNum" width="120"></el-table-column>
          <el-table-column label="推广人数量(可分发人数量)" prop="promoteNum" width="130"></el-table-column>
          <el-table-column label="浏览数PV" prop="viewPv" width="100"></el-table-column>
          <el-table-column label="用户数UV" prop="viewUv" width="100"></el-table-column>
          <el-table-column label="总认筹数" prop="submitNum" width="100"></el-table-column>
          <el-table-column label="总核销数" prop="useNum" width="100"></el-table-column>
          <el-table-column label="朋友圈浏览量" prop="timelineViewNum" width="120"></el-table-column>
          <el-table-column label="朋友圈预定数" prop="timelineBookNum" width="120"></el-table-column>
          <el-table-column label="微信群浏览量" prop="groupViewNum" width="120"></el-table-column>
          <el-table-column label="微信群预定数" prop="groupBookNum" width="120"></el-table-column>
          <el-table-column label="海报浏览量" prop="postViewNum" width="120"></el-table-column>
          <el-table-column label="海报预定数" prop="postBookNum" width="120"></el-table-column>
          <el-table-column label="关注公众号总数" prop="subscribeNum" width="120"></el-table-column>
        </el-table>
      </div>
      <div class="pagination" v-show="activityPaging.page && activityPaging.page.total">
        <el-pagination
          :current-page.sync="activityPaging.index"
          :page-size.sync="activityPaging.size"
          layout="sizes, total, prev, pager, next, jumper"
          :total.sync="activityPaging.total"
          :page-sizes="[10, 30, 50, 100]"
          @current-change="activityPagingIndexChange"
          @size-change="activityPagingSizeChange">
        </el-pagination>
      </div>
    </div>
    <div class="details">
      <div class="title">
        <h3 class="inline-block mgr10">明细数据</h3>
        <el-select v-model="detailsMode" size="mini" placeholder="请选择" @change="detailsModeChange">
          <el-option label="传播明细" value="1"></el-option>
          <el-option label="参与明细" value="2"></el-option>
        </el-select>
      </div>
      <div class="list">
        <el-table
          stripe
          v-show="detailsMode === '1'"
          v-loading="loading2"
          element-loading-text="拼命加载中"
          :data="detailsTbData.list">
          <el-table-column label="活动标题" prop="name" min-width="120" fixed></el-table-column>
          <el-table-column label="活动时间" prop="activityDate" :formatter="getActivityDate" width="200"></el-table-column>
          <el-table-column label="活动状态" prop="status" min-width="120"></el-table-column>
          <el-table-column label="分公司" prop="departmentName" min-width="120"></el-table-column>
          <el-table-column label="推广人ID" prop="userId" min-width="100"></el-table-column>
          <el-table-column label="销售代表名字" prop="username" min-width="120"></el-table-column>
          <el-table-column label="电话" prop="phone" min-width="120"></el-table-column>
          <el-table-column label="浏览量PV" prop="viewPv" min-width="100"></el-table-column>
          <el-table-column label="用户数UV" prop="viewUv" min-width="100"></el-table-column>
          <el-table-column label="认筹数" prop="submitNum" min-width="80"></el-table-column>
          <el-table-column label="核销数" prop="useNum" min-width="80"></el-table-column>
          <el-table-column label="朋友圈浏览量" prop="timelineViewNum" min-width="120"></el-table-column>
          <el-table-column label="朋友圈预定量" prop="timelineBookNum" min-width="120"></el-table-column>
          <el-table-column label="微信群浏览量" prop="groupViewNum" min-width="120"></el-table-column>
          <el-table-column label="微信群预定量" prop="groupBookNum" min-width="120"></el-table-column>
          <el-table-column label="海报浏览量" prop="postViewNum" width="100"></el-table-column>
          <el-table-column label="海报预定数" prop="postBookNum" min-width="100"></el-table-column>
          <el-table-column label="关注公众号总数" prop="subscribeNum" min-width="120"></el-table-column>
        </el-table>
        <el-table
          stripe
          v-show="detailsMode === '2'"
          v-loading="loading2"
          element-loading-text="拼命加载中"
          cell-class-name="table-cell"
          :data="detailsTbData.list">
          <el-table-column label="活动标题" prop="name" min-width="120" fixed></el-table-column>
          <el-table-column label="分公司" prop="departmentName" min-width="120"></el-table-column>
          <el-table-column label="推广人ID" prop="userId" min-width="100"></el-table-column>
          <el-table-column label="推广人名称" prop="username" min-width="120"></el-table-column>
          <el-table-column label="电话" prop="phone" min-width="120"></el-table-column>
          <el-table-column label="用户OPENID" prop="openid" min-width="120"></el-table-column>
          <el-table-column label="用户名" prop="customerName" min-width="100"></el-table-column>
          <el-table-column label="用户电话" prop="customerPhone" min-width="120"></el-table-column>
          <el-table-column label="认筹时间" prop="submitTime" width="180"></el-table-column>
          <el-table-column label="金额" prop="price" width="180" :formatter="formatPrice"></el-table-column>
          <el-table-column label="核销时间" prop="useTime" width="180"></el-table-column>
          <el-table-column label="核销人OPENID" prop="useSaleId" min-width="120"></el-table-column>
          <el-table-column label="核销人" prop="useSaleName" min-width="100"></el-table-column>
          <el-table-column label="核销主体" prop="userSaleDepartmentName" min-width="120"></el-table-column>
        </el-table>
      </div>
      <div class="pagination" v-show="detailsTbData.page && detailsTbData.page.total">
        <el-pagination
          :current-page.sync="detailsPaging.index"
          :page-size.sync="detailsPaging.size"
          layout="sizes, total, prev, pager, next, jumper"
          :total.sync="detailsPaging.total"
          :page-sizes="[10, 30, 50, 100]"
          @current-change="detailsPagingIndexChange"
          @size-change="detailsPagingSizeChange">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    getReportDepartment,
    getBranchCompanyCollect,
    getSpreadDetails,
    getPartakeDetails
  } from "@/service/getData";
  import env from '@/config/env'

  export default {
    data() {
      return {
        exportLink: '',
        dateRanges: [],
        departmentId: '',
        departmentList: [],
        detailsMode: '1',
        spreadDetailsList: [],
        filterKeyword: '',
        activityTbData: {
          list: [],
          page: {}
        },
        detailsTbData: {
          list: [],
          page: {}
        },
        loading1: false,
        loading2: false,
        activityPaging: {
          index: 1,
          size: 10,
          total: 0
        },
        detailsPaging: {
          index: 1,
          size: 10,
          total: 0
        },
        searchBtnLoading: false
      }
    },
    computed: {
      searchRules() {
        const flag = this.dateRanges && this.dateRanges.length > 1
        const dateStart = flag ? Math.floor(this.dateRanges[0].getTime() / 1000) : ''
        const dateEnd = flag ? Math.floor(this.dateRanges[1].getTime() / 1000) : ''
        return {
          startTime: dateStart,
          endTime: dateEnd,
          departmentId: this.departmentId,
          search: this.filterKeyword
        }
      },
      exportUrl() {
        const query = Object.assign({}, this.searchRules, {
          page: 1,
          size: 500000,
          UBToken: localStorage.getItem('UBToken')
        })
        let params = []
        for (let key in query) {
          query.hasOwnProperty(key) && params.push(`${key}=${query[key]}`)
        }
        const url = '/marketing/activity/manager/exportDataNew?' + params.join('&')
        return env.baseUrl3 + url
      }
    },
    created() {
      this.init()
    },
    methods: {

      // 初始化页面
      init() {
        this.autoFillDate()
        this.getDepartment()
        this.getActivityList()
        this.getDetailsList()
      },

      // 获取分公司
      async getDepartment() {
        const res = await getReportDepartment()
        this.departmentList = res.data.data || []
      },

      // 自动设置默认日期
      autoFillDate() {
        const dateStart = new Date()
        const dateEnd = new Date()
        dateStart.setDate(1)
        dateStart.setHours(0, 0, 0, 0)
        dateEnd.setHours(23, 59, 59, 999)
        this.dateRanges = [dateStart, dateEnd]
      },

      // 选择日期
      dateChange(value) {
        this.dateRanges = value
      },

      // 搜索
      handleSearch() {
        this.activityPaging.index = 1
        this.activityPaging.total = 0
        this.detailsPaging.index = 1
        this.detailsPaging.total = 0
        this.searchBtnLoading = true
        this.getActivityList()
        this.getDetailsList()
      },

      // 切换明细数据
      detailsModeChange() {
        this.detailsPaging.index = 1
        this.detailsTbData = {
          list: [],
          page: {}
        }
        this.detailsPaging.total = 0
        this.getDetailsList()
      },

      // 获取活动数据表列表
      async getActivityList() {
        if(!this.dateRanges || !this.dateRanges.length) {
          this.alert('请选择活动时间段！')
          return false
        }
        this.loading1 = true
        const rules = Object.assign({}, this.searchRules, {
          page: this.activityPaging.index,
          size: this.activityPaging.size
        })
        getBranchCompanyCollect(rules).then(res => {
          const data = res.data.data
          if(data) {
            this.activityTbData = data
            this.activityPaging.total = data.page.total
          }
          this.loading1 = false
          this.searchBtnLoading = false
        }).catch(err => {
          this.loading1 = false
          this.searchBtnLoading = false
        })
      },

      // 获取明细数据表列表
      async getDetailsList() {
        if(!this.dateRanges || !this.dateRanges.length) {
          this.alert('请选择搜索时间段！')
          return false
        }
        this.loading2 = true
        const rules = Object.assign({}, this.searchRules, {
          page: this.detailsPaging.index,
          size: this.detailsPaging.size
        })
        const fn = this.detailsMode === '1' ? getSpreadDetails : getPartakeDetails
        fn(rules).then(res => {
          const data = res.data.data
          if(data) {
            this.detailsTbData = res.data.data
            this.detailsPaging.total = res.data.data.page.total
          }
          this.loading2 = false
          this.searchBtnLoading = false
        }).catch(err => {
          this.loading2 = false
          this.searchBtnLoading = false
        })
      },

      // 活动数据表当前页码改变
      activityPagingIndexChange() {
        this.getActivityList()
      },

      // 活动数据表每页容量改变
      activityPagingSizeChange(value) {
        this.activityPaging.index = 1
        this.activityPaging.size = value
        this.getActivityList()
      },

      // 明细数据表当前页码改变
      detailsPagingIndexChange() {
        this.getDetailsList()
      },

      // 明细数据表每页容量改变
      detailsPagingSizeChange(value) {
        this.detailsPaging.index = 1
        this.detailsPaging.size = value
        this.getDetailsList()
      },

      // 日期格式化
      dateFormat(date) {
        if (date) {
          return this.$date.format(new Date(date), 'YYYY-MM-DD')
        }
      },

      // 活动时间
      getActivityDate(row, column, cellValue, rowIndex) {
        const dateStart = this.dateFormat(row.startTime * 1000)
        const dateEnd = this.dateFormat(row.endTime * 1000)
        return dateStart + ' 至 ' + dateEnd
      },

      //
      formatPrice(row, column, cellValue, rowIndex) {
        let price = ((cellValue || 0) / 100).toFixed(2)
        return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      },

      //
      alert(title) {
        this.$message.closeAll()
        this.$message.warning(title)
        this.searchBtnLoading = false
      },

      // 合计
      getSum({columns, data}) {
        const sum = (array) => array.reduce((acc, item) => isNaN(Number(item)) ? acc : acc + item, 0)
        let result = ['合计']
        columns.forEach((column, index) => {
          if(index === 0) {
            return
          }
          const values = data.map(row => Number(row[column.property]))
          const isAllNaN = values.every(value => isNaN(value))
          result.push(isAllNaN ? '--' : sum(values))
        })
        return result
      }

    }
  }
</script>

<style lang="scss" scoped>

  .clearfix:after {
    content: "";
    display: block;
    height: 0;
    visibility: hidden;
    clear: both;
  }

  .mgr10 {
    margin-right: 10px;
  }

  .inline-block {
    display: inline-block;
  }

  .filter {
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 1px solid #ccc;
  }

  .left {
    float: left;
  }

  .right {
    float: right;
  }

  .date-picker {
    width: 260px;
  }

  .searchbox {
    width: 340px;
  }

  .details {
    margin-top: 50px;
  }

  .title {
    padding: 15px 0;
    h3 {
      font-size: 16px;
    }
  }

  .report /deep/ {
    .list tr th,
    .list tr td{
      text-align: center;
    }
  }

  .activity-list /deep/ {
    .el-table--striped .el-table__body tr.el-table__row--striped:last-child td{
      background: #dcdcdc;
      font-weight: bold;
    }
    .el-table__body-wrapper{
      table{
        tr:last-child{
          td{
            background: #dcdcdc;
            .cell{
              font-weight: bold;
            }
          }
        }
      }
    }
  }


</style>
